<?php

namespace addons\facrm\controller\facrm\business;

use addons\facrm\library\BackendApi;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 商机管理
 */
class Index extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['product'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Business');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 商机列表
     * @ApiParams(name="customer_id", type="int", required=false, description="客户id")
     */
    public function index()
    {
        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'business')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter_w['owner_user_id'] = $this->auth->id;
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 7;
        if (isset($filter['scene_id'])) {
            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            switch ($filter['scene_id']) {
                case 7:
                    //全部客户 超级管理员不做限制
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                    $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
                case 8:
                    //我的商机
                    $filter_w['owner_user_id'] = $this->auth->id;
                    break;
                case 9:
                    //下属商机
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    $filter_w['owner_user_id'] = ['in', $this->childrenAdminIds];
                    break;
                default://其它的还做 TODO
                    $filter_w['owner_user_id'] = $this->auth->id;

            }

            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }

        $customer_id = $this->request->param("customer_id");
        if ($customer_id) {
            $filter_w['customer_id'] = $customer_id;
        }
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'ownerUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();

        $result = array("rows" => $list);
        $this->success('',array( "rows" => $list,'scene'=>$scene_list));
    }

    /**
     * 添加
     * @ApiMethod (POST)
     * @ApiParams(name="customer_id", type="int", required=true, description="客户id")
     * @ApiParams(name="name", type="string", required=true, description="商机名称")
     * @ApiParams(name="next_time", type="string", required=false, description="下次跟进时间如：2021-6-10 16:17:49")
     * @ApiParams(name="deal_time", type="string", required=false, description="预计成交时间如：2021-6-10 16:17:49")
     * @ApiParams(name="money", type="number", required=false, description="客户预算金额")
     * @ApiParams(name="remark", type="string", required=false, description="备注")
     * @ApiParams(name="discount_rate", type="int", required=false, description="优惠率")
     * @ApiParams(name="total_price", type="int", required=false, description="商品金额")
     * @ApiParams(name="product[0][product_id]", type="int", required=false, description="商品id")
     * @ApiParams(name="product[0][nums]", type="int", required=false, description="数量")
     * @ApiParams(name="product[0][price]", type="int", required=false, description="商品单价")
     * @ApiParams(name="product[0][subtotal]", type="int", required=false, description="商品小计")
     * @ApiParams(name="product[0][remarks]", type="remark", required=false, description="备注")
     * @ApiBody ("产品多个的话可以在product[0]数字上变化")
     * @return mixed
     */
    public function add()
    {
        if (!$this->request->isPost())
            $this->error(__('提交方式错误'));

        $params = $this->request->post();
        if (!isset($params['customer_id']))
            $this->error(__('请选择客户'));

        $customer = model('\app\admin\model\facrm\Customer');
        $row_c = $customer->get($params['customer_id']);

        if (!$row_c)
            $this->error(__('没有找到客户'));

        if (!$this->auth->checkCustomerAuth($row_c, $this->auth)) {
            $this->error(__('You have no permission'));
        }


        $result = false;
        Db::startTrans();
        try {
            $params['next_time'] = isset($params['next_time'])&&$params['next_time'] ? strtotime($params['next_time']) : 0;
            $params['deal_time'] = isset($params['deal_time'])&&$params['deal_time'] ? strtotime($params['deal_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $row_c['owner_user_id'],
                'type_id' => '1',
                'status' => 1,
            ]);
			if(isset($params['product'])){
                unset($params['product']);//不知道allowField过滤器为什么失效了，手动过滤一下
            }
            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $result = $this->model->validateFailException(true)->validate($name . '.add')->allowField(true)->save($params);

            //添加商机产品
            $product_data = ($this->request->post("product/a"));
            if ($product_data){
                $business_id = $this->model->id;
                foreach ($product_data as &$row) {
                    $row['business_id'] = $business_id;
                }
                $this->model->product()->saveAll($product_data);
            }

            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success(__("添加成功"));
        } else {
            $this->error(__('No rows were inserted'));
        }
    }

    /**
     * 修改
     * @ApiMethod (POST|GET)
     * @ApiParams(name="customer_id", type="int", required=true, description="客户id")
     * @ApiParams(name="name", type="string", required=true, description="商机名称")
     * @ApiParams(name="next_time", type="string", required=false, description="下次跟进时间如：2021-6-10 16:17:49")
     * @ApiParams(name="deal_time", type="string", required=false, description="预计成交时间如：2021-6-10 16:17:49")
     * @ApiParams(name="money", type="number", required=false, description="客户预算金额")
     * @ApiParams(name="remark", type="string", required=false, description="备注")
     * @ApiParams(name="discount_rate", type="int", required=false, description="优惠率")
     * @ApiParams(name="total_price", type="int", required=false, description="商品金额")
     * @ApiParams(name="product[0][product_id]", type="int", required=false, description="商品id")
     * @ApiParams(name="product[0][nums]", type="int", required=false, description="数量")
     * @ApiParams(name="product[0][price]", type="int", required=false, description="商品单价")
     * @ApiParams(name="product[0][subtotal]", type="int", required=false, description="商品小计")
     * @ApiParams(name="product[0][remarks]", type="remark", required=false, description="备注")
     * @ApiBody ("get是获取商机信息,产品多个的话可以在product[0]数字上变化。要修改的字段提交过来")
     * @param null $id
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($id,['product.info','ownerUser'=>function($query){
        return $query->field('id,username,nickname');
    }]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if (!$this->auth->checkBusinessAuth($row, $this->auth)) {
            $this->error(__('您没有权限'));
        }
        if (!$this->auth->checkCustomerAuth($row->customer, $this->auth)) {
            $this->error(__('您没有权限:客户权限'));
        }
        if ($this->request->isPost()) {

            $params = $this->request->post();
            if ($params) {

                $params['next_time'] = isset($params['next_time'])&&$params['next_time'] ? strtotime($params['next_time']) : 0;
                $params['deal_time'] = isset($params['deal_time'])&&$params['deal_time'] ? strtotime($params['deal_time']) : 0;
                $result = false;
                Db::startTrans();

                try {
                    if ($row->is_end != 0) exception(__("不能修改的状态"));
                    if (isset($params['is_end'])&&$params['is_end'] == 1) exception(__("不能手动改成成交状态，请添加合同！"));
                    $business_id = $row->id;
					if(isset($params['product'])){
						unset($params['product']);//不知道allowField过滤器为什么失效了，手动过滤一下
					}
                    $result = $row->allowField(true)->save($params);
                    if ($result) {
                        //更新产品,先全部删除再添加
                        $productModel = model('\app\admin\model\facrm\business\Product');
                        $this->model->product()->where('business_id', $business_id)->delete();
                        $product_data = ($this->request->post("product/a"));
                        if ($product_data){
                            foreach ($product_data as &$r) {
                                $r['business_id'] = $business_id;
                            }
                            $productModel->saveAll($product_data);
                        }

                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        return $this->success('', $row);

    }

    /**
     * 删除
     * @ApiMethod (POST)
     * @ApiParams(name="ids", type="int", required=true, description="商机ids,多个用逗号隔开")
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success(__("删除成功"));
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



}
